<template>
	<cl-crud ref="crud" @load="onLoad" :on-refresh="onRefresh">
		<cl-pagefull>
			<template #head>
				<el-row type="flex">
					<cl-filter-group v-model="search" @reset="changeBiz">
						<cl-filter label="所属事业部">
							<cl-select
								v-model="search.biz_id"
								placeholder="请选择"
								filterable
								@change="changeBiz"
							>
								<el-option
									v-for="item in business"
									:key="item.biz_id"
									:label="item.biz_name"
									:value="item.biz_id"
								/>
							</cl-select>
						</cl-filter>
						<cl-filter label="分公司">
							<cl-select
								v-model="search.company_id"
								placeholder="请选择"
								clearable
								filterable
								@change="refresh"
							>
								<el-option label="全部" value="" />
								<el-option
									v-for="item in bizRefData.company"
									:key="item.company_id"
									:label="item.company_name"
									:value="item.company_id"
								/>
							</cl-select>
						</cl-filter>
						<cl-filter label="所属城市">
							<cl-select
								v-model="search.city_id"
								placeholder="请选择"
								filterable
								clearable
								@change="refresh"
							>
								<el-option label="全部" value="" />
								<el-option
									v-for="item in cityList"
									:key="item.id"
									:label="item.name"
									:value="item.id"
								/>
							</cl-select>
						</cl-filter>
						<cl-filter label="所属门店">
							<cl-select
								v-model="search.dept_id"
								placeholder="全部"
								filterable
								clearable
								multiple
								collapse-tags
								@change="refresh"
							>
								<!-- <el-option label="全部" value="" /> -->
								<el-option
									v-for="item in bizRefData.shop_childs"
									:key="item.dept_id"
									:label="item.dept_name"
									:value="item.dept_id"
								/>
							</cl-select>
						</cl-filter>
						<cl-filter label="品牌">
							<cl-select
								v-model="search.bra_id"
								placeholder="全部"
								clearable
								filterable
								style="width: 160px"
								@change="refresh"
								multiple
								collapse-tags
							>
								<el-option
									v-for="item in bizRefData.brand"
									:key="item.bra_id"
									:label="item.bra_name"
									:value="item.bra_id"
								/>
							</cl-select>
						</cl-filter>

						<cl-filter label="客户关键字">
							<cl-keyword-search
								:value="{
									search_content: search.search,
									keyword_type: search.keyword_type
								}"
								@update="updateKeyword"
							/>

							<!-- <el-input
								v-model="search.search"
								placeholder="手机号/微信号/客户名称/会员号"
								clearable
								style="width: 220px"
								@change="refresh"
							/> -->
						</cl-filter>
						<cl-filter label="下定日期">
							<cl-date-picker
								v-model="search.time"
								type="daterange"
								range-separator="至"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								value-format="yyyy-MM-dd"
								style="width: 210px"
								clearable
								@change="refresh"
								:picker-options="pickerOptions"
							/>
						</cl-filter>
						<cl-filter label="推送日期">
							<cl-date-picker
								v-model="search.ptime"
								type="daterange"
								range-separator="至"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								value-format="yyyy-MM-dd"
								style="width: 210px"
								clearable
								@change="refresh"
								:picker-options="pickerOptions"
							/>
						</cl-filter>
						<cl-filter label="接收日期">
							<cl-date-picker
								v-model="search.gtime"
								type="daterange"
								range-separator="至"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								value-format="yyyy-MM-dd"
								style="width: 210px"
								clearable
								@change="refresh"
								:picker-options="pickerOptions"
							/>
						</cl-filter>
						<!-- <cl-filter label="推送状态">
							<cl-select v-model="search.is_push" placeholder="推送状态" style="width:120px">
								<el-option label="全部" :value="0" />
								<el-option
									v-for="item in pushStatusList"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								/>
							</cl-select>
						</cl-filter> -->
						<cl-filter label="接收状态">
							<cl-select
								v-model="search.is_get"
								placeholder="接收状态"
								style="width: 120px"
								@change="refresh"
							>
								<el-option label="全部" :value="0" />
								<el-option
									v-for="item in getStatusList"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								/>
							</cl-select>
						</cl-filter>
						<cl-filter label="定金类型">
							<cl-select
								v-model="search.cus_type"
								placeholder="定金类型"
								style="width: 120px"
								clearable
								@change="refresh"
							>
								<el-option label="全部" value="" />
								<el-option label="新客" :value="1" />
								<el-option label="老客" :value="2" />
							</cl-select>
						</cl-filter>
						<cl-filter label="接收部门">
							<cl-cascader
								clearable
								v-model="search.after_dept_id"
								:options="deptList"
								:props="{
									value: 'dept_id',
									label: 'dept_name'
								}"
								filterable
								style="width: 100%"
								@change="changeDept"
							/>
						</cl-filter>
						<cl-filter label="接收人">
							<cl-select
								v-model="search.get_user_id"
								placeholder="请选择"
								clearable
								style="width: 100%"
							>
								<el-option
									v-for="item in userList"
									:key="item.user_id"
									:label="item.user_name"
									:value="item.user_id"
								/>
							</cl-select>
						</cl-filter>
						<cl-filter label="推送部门">
								<cl-cascader
									clearable
									v-model="search.push_dept_id"
									:options="preDeptList"
									:props="{
										value: 'dept_id',
										label: 'dept_name',
										checkStrictly: true
									}"
									filterable
									@change="changePushDept"
								/>
							</cl-filter>
							<cl-filter label="推送人员">
								<cl-select
									v-model="search.user_id"
									placeholder="请选择"
									filterable
									style="width: 150px"
									clearable
								>
									<el-option label="全部" value="" />
									<el-option
										v-for="item in preUserList"
										:key="item.user_id"
										:label="item.user_name"
										:value="item.user_id"
									/>
								</cl-select>
							</cl-filter>
					</cl-filter-group>
					<cl-flex1 />
					<cl-table-handle @export-file="exportFile" :isShow="false" />
				</el-row>
			</template>

			<el-row>
				<!-- 数据表格 -->
				<cl-table v-bind="table" id="EarnestReceiveForm" ref="table">
					<cl-empty slot="empty" />
					<template #column-customer="{ scope: { row } }">
						<cl-customer
							:gender="row.cus_sex"
							:name="row.cus_name"
							:cusId="row.cus_id+''|| '-'"
							:avatar="row.cus_img"
							:id_join_type="row.id_join_type"
						/>
					</template>
					<template #column-cus_type="{ scope: { row } }">
						<div
							class="cus_type"
							:class="{
								'color-primary': row.cus_type == 1,
								old: row.cus_type == 2,
								'color-danger': row.cus_type == 3,
								'color-warning': row.cus_type == 4
							}"
						>
							{{ row.cus_type | constFilter("CUS_TYPE") }}
						</div>
					</template>
					<template #column-push_time="{ scope: { row } }">
						<div v-if="row.is_push">
							{{ row.push_time }}
						</div>
					</template>
					<template #column-opt="{ scope: { row } }">
						<div class="flex flex-align-start" v-if="row.is_get == 0">
							<el-button
								type="primary"
								@click.stop="receiveClick(row)"
								v-auth="'store_cusgetdeposit_receive'"
							>
								接收
							</el-button>
							<el-button
								@click.stop="refuseClick(row)"
								v-auth="'store_cusgetdeposit_reject'"
								>拒接</el-button
							>
							<el-button
								@click.stop="openCusDetail(row)"
								v-auth="'store_cusdetailindex_look'"
								>详情</el-button
							>
						</div>
						<div v-else>{{ row.is_get == 1 ? "接收" : "拒接" }}  
							<el-button
								@click.stop="openCusDetail(row)"
								v-auth="'store_cusdetailindex_look'"
								>详情</el-button
							>
						</div>
					</template>
				</cl-table>
			</el-row>

			<template #foot>
				<el-row type="flex">
					<cl-flex1 />
					<!-- 分页控件 -->
					<cl-pagination />
				</el-row>
			</template>
		</cl-pagefull>
	</cl-crud>
</template>

<script>
import { mapState } from "vuex";
import dayjs from "dayjs";
import { exportExcel } from "@/utils/excel";
import { delEmptyChildren } from "@/utils";
import { last } from "cl-admin/utils";

export default {
	name: "CusOtherEarnestReceive",
	inject: ["$layout"],
	data() {
		return {
			pickerOptions: {
					disabledDate(time) {
						return time.getTime() > Date.now();
					}
			},
			// 表格配置
			table: {
				"context-menu": ["refresh"],
				columns: [
					{ label: "客户信息", prop: "customer", width: 210,showOverflowTooltip: true, fixed: true },
					{ label: "门店", prop: "dept_name",showOverflowTooltip: true, minWidth: 120 },
					// { label: "定金类型", prop: "cus_type", minWidth: 80 },
					{ label: "定金金额（￥）", prop: "dep_amount", minWidth: 120 },
					{ label: "下定金日期", prop: "pay_date", minWidth: 100 },
					{ label: "推送人", prop: "user_name", minWidth: 120 },
					{ label: "推送时间", prop: "push_time", minWidth: 140 },
					{ label: "接收时间", prop: "get_time",showOverflowTooltip: true, minWidth: 140 },
					{ label: "接收人", prop: "get_user_name",showOverflowTooltip: true, minWidth: 140 },
					{ label: "接收状态", prop: "is_get", width: 100  },
					{ label: "操作", prop: "opt", width: 210, fixed: "right" }
				]
				// on: {
				// 	"row-click": (row) => {
				// 		this.$layout.openCusDetail(row, "earnest");
				// 	}
				// }
			},
			pushStatusList: [
				{ value: 1, label: "推送" },
				{ value: 2, label: "未推送" }
			],
			getStatusList: [
				{ value: 1, label: "接收" },
				{ value: 2, label: "拒接" },
				{ value: 3, label: "未接收" }
			],
			search: {
				search: "",
				biz_id: "",
				company_id: "",
				city_id: "",
				after_dept_id: [], //售中部门
				get_user_id: "", //接收人员id
				dept_id: [], // 门店ID
				is_get: 0, // 3未接收 1接收 2拒接' 0全部
				is_push: 1, // 0全部1推送 2未推送
				time: [dayjs().format("YYYY-MM-DD"), dayjs().format("YYYY-MM-DD")],
				btime: "", // 定金日期开始时间
				etime: "", // 定金日期结束时间
				ptime: [],
				ptime_s: "", // 推送开始时间
				ptime_e: "", // 推送结束时间
				gtime: [],
				gtime_s: "", // 接收开始时间
				gtime_e: "", // 接收结束时间
				pagedata: 1, // 分页数据是否开启，1-开启
				cus_type: "", // 定金类型
				bra_id: [],
				takeover: 1, //状态判断
				keyword_type: 4,
				user_id: "", //售前人员
				push_dept_id: "" //售前部门
			},
			deptList: [],
			userList: [],
			cityList: [],
			preDeptList: [],
			preUserList: []
		};
	},
	computed: {
		...mapState("common", ["visibleCusDetail", "cusFormSubmit"]),
		bizRefData() {
			const { biz_id } = this.search;
			return this.getBizRefData(biz_id);
		}
	},
	watch: {
		visibleCusDetail(v) {
			!v && this.refresh(false);
		},
		cusFormSubmit(v) {
			v && this.refresh();
		}
	},
	created() {
		this.search.biz_id = this.getCurrBiz();
		this.init();
		this.getCityList();
	},
	methods: {
		async getPreDept() {
			const { biz_id } = this.search;
			this.preDeptList = await this.$service.dept.preDept({
				parent_id: 0,
				biz_id
			});
		},
		async getUserList() {
			const { biz_id, push_dept_id } = this.search;
			this.preUserList = [];
			if (!biz_id) return;
			const data = await this.$service.user.deptuserlists({
				biz_id,
				dept_id: last(push_dept_id)
			});
			this.preUserList = data;
		},
		changePushDept() {
			this.search.user_id = "";
			this.getUserList();
			this.refresh();
		},
		updateKeyword(e) {
			this.search.search = e.search_content.trim();
			this.search.keyword_type = e.keyword_type;
		},
		async getCityList() {
			const { biz_id } = this.search;
			this.$service.spread.getbizcitys({ biz_id }).then(data => {
				let list = (data || []).map(v => ({ ...v, label: v.name, value: v.id }));
				this.cityList = list;
			});
		},
		async init() {
			const { biz_id } = this.search;

			this.updateBizRefData(biz_id);
			this.deptList = delEmptyChildren(
				(await this.$store.dispatch("common/getDept", {
					biz_id,
					post: 2,
					needAll: false,
					needCascader: true
				})) || []
			);

			this.getPreDept();
			this.getUserList();
		},
		async onRefresh(params, { next, render, done }) {
			// if (!params.bra_id.length) {
			// 	this.$message.error("请选择品牌");
			// 	return done();
			// }
			if(params.search&&params.search.length < 2){
				this.$message.error("使用关键字搜索时中文至少2位查询，其他至少4位可查询");
				return done();
			}
        
			// this.loading = true;
			const { data } = await next(params)
			// console.log(data)
			// render(data);
		},
		onLoad({ ctx, app }) {
			ctx.service(this.$service.deposit)
				.set("dict", {
					api: { page: "mine" }
				})
				.done();
			app.refresh(this.search);
		},
		// crud刷新
		refresh(reset = true) {
			console.log('11111111111111111111')
			let params = { ...this.search };
			if (reset) {
				params.page = 1;
			}
			this.$refs.crud.refresh(params);
			this.$nextTick(() => {
				this.$refs.table?.calcMaxHeight?.();
			});
		},
		changeBiz() {
			this.search = {
				...this.search,
				company_id: "",
				after_dept_id: [],
				get_user_id: "",
				bra_id: [],
				dept_id: [],
				city_id: ""
			};
			// this.getShopList();
			this.init();
			// this.refresh();
		},
		changeDept() {
			this.search.get_user_id = "";
			this.getManageDeptUser();
		},
		// 获取接收人
		async getManageDeptUser() {
			const { after_dept_id, biz_id } = this.search;
			// if (Array.isArray(dept_id)) {
			// 	dept_id = dept_id.join();
			// }
			this.userList = [];
			const data = await this.$service.user.deptuserlists({
				biz_id,
				dept_id: after_dept_id[1],
				post: 2
			});
			this.userList = data;
		},
		// 客户详情
		async openCusDetail(row) {
			this.$layout.openCusDetail(row, "earnest");
		},
		// 接收
		async receiveClick(row) {
			const data = await this.$service.deposit.receive({ dep_id: row.dep_id });
			row.is_get = data.is_get;
			this.$message.success("接收成功");
			this.refresh()
		},
		// 拒接
		refuseClick(row) {
			this.$crud.openForm({
				title: "拒接",
				width: "500px",
				props: {
					"label-position": "top"
				},
				items: [
					{
						label: "拒接原因",
						prop: "reject_reason",
						component: {
							name: "el-input",
							attrs: { placeholder: "请输入拒接原因" },
							props: { type: "textarea", rows: 2 }
						},
						rules: { required: true, message: "拒接原因不能为空" }
					}
				],
				op: { saveButtonText: "提交" },
				on: {
					submit: async (data, { close, done }) => {
						try {
							const res = await this.$service.deposit.refuse({
								dep_id: row.dep_id,
								reject_reason: data.reject_reason
							});
							row.is_get = res.is_get;
							this.$message.success("拒接成功");
							this.refresh();
							close();
						} catch (error) {
							done();
						}
					}
				}
			});
		},
		// 导出EXCEl
		exportFile() {
			exportExcel("#EarnestReceiveForm");
		}
	}
};
</script>

<style lang="scss" scoped>
</style>
